#'
#' calcualte intraspecific trait variance
#'
#'
#' @param  com a community object
#' @param traits a vector of trait names need to be calculate intraspecific trait variation
#'
#'
#'
#'@examples
#'sp=paste("sp",1:4,sep="")
#'species=sample(rep(sp,1:4),sum(1:4))
#'plotdim=c(10,8)
#'x=runif(length(species),0,plotdim[1])
#'y=runif(length(species),0,plotdim[2])
#'com=community(species=species,x=x,y=y,plotdim=plotdim,traits=data.frame(dbh=runif(length(species),1,10)))
#'
#'
#'
wITV=function(com,traits,relative=TRUE){
  re=numeric()
  for(i in 1:length(traits)){
    re[i]=wITV_onetrait(com,traits[i],relative)
  }
  return(re)
}

wITV_onetrait=function(com,trait,relative){
  traits=get_trait_names(com)
  if(trait %in% traits){
    spab=species_abundance(com)
    p=spab/sum(spab)
    tind=com[,trait]
    tj=tapply(tind,com$species,mean,na.rm=T)
    tjind=com$species
    levels(tjind)=tj
    tjind=as.numeric(as.character(tjind))
    intra=sum(p/spab*tapply((tind-tjind)^2,com$species,sum,na.rm=T),na.rm=T)
    if(relative){
      inter=sum(p*(tj-sum(p*tj,na.rm=T))^2,na.rm=T)
      return(intra/(intra+inter))
    }else{
      return(intra)
    }
    
  }else{
    warning(paste("No trait named",trait,"was found in the given community"))
    return(NA)
  }
  
}